﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Decoration;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.StaffApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.StaffAPI
{
    [ApiAuthentication]
    public class StaffDecoratiomRunningController : BaseApiController
    {
        public IDecorationRunningsContract DRContract { get; set; }
        public IStaffContract SContract { get; set; }
        public IDecorationRunningsStateContract DRSContract { get; set; }
        public IImagesContract IContract { get; set; }

        [Description("API-装修订单历史列表")]
        public IHttpActionResult ttGetDecoractionRunningsList([FromBody]DecorationRunningsParamsModel entity)
        {
            DateTime bt = entity.BeginTime;
            DateTime et = entity.EndTime.AddDays(1);

            Model.DbModels.Organization.Staff staff = SContract.GetByKey(BaseWebApiExt.GetStaffIDByToken());
            var query = from n in DRContract.Entities
                        join u1 in SContract.Entities on n.OriginStaffID equals u1.Id into eu1
                        from eu1d in eu1.DefaultIfEmpty()
                        join u2 in SContract.Entities on n.SellStaffID equals u2.Id into eu2
                        from eu2d in eu2.DefaultIfEmpty()
                        join s in DRSContract.Entities on n.State equals s.Id into s2
                        from s2d in s2.DefaultIfEmpty()
                        where (n.OriginStaffID == staff.Id || n.SellStaffID == staff.Id) && n.SubscribeTime >= bt && n.SubscribeTime <= et && n.AgentID == staff.AgentID
                        select new DecorationRunningListModel
                        {
                            BandSawTime = n.BandSawTime,
                            DecorationCompanyID = n.DecorationCompanyID,
                            DecorationCompanyName = n.DecorationCompanyName == null ? "" : n.DecorationCompanyName,
                            CompleteTime = n.CompleteTime,
                            CustomerID = n.CustomerID,
                            CustomerName = n.CustomerName == null ? "" : n.CustomerName,
                            CustomerPhone = n.CustomerPhone == null ? "" : n.CustomerPhone,
                            DownPaymentTime = n.DownPaymentTime,
                            FilingTime = n.FilingTime,
                            Id = n.Id,
                            IntermediaryID = n.IntermediaryID,
                            IntermediaryName = n.IntermediaryName == null ? "" : n.IntermediaryName,
                            OriginStaffID = n.OriginStaffID,
                            OriginStaffName = eu1d.Name == null ? "" : eu1d.Name,
                            Remark = n.State == 3 ? (n.FilingAuditingRemark == null ? "" : n.FilingAuditingRemark) : (n.Remark == null ? "" : n.Remark),
                            SellStaffID = n.SellStaffID,
                            SellStaffName = eu2d.Name == null ? "" : eu2d.Name,
                            State = n.State,
                            StateName = s2d.Name == null ? "" : s2d.Name,
                            SubscribeTime = n.SubscribeTime,
                            TotalPrice = n.TotalPrice,
                            UserID = n.UserID,
                            UserName = n.UserName == null ? "" : n.UserName,
                            UserPhone = n.UserPhone == null ? "" : n.UserPhone,
                            Area = n.Area,
                            CustomerAddress = n.CustomerAddress == null ? "" : n.CustomerAddress,
                            //BandSawImage = IContract.Entities.Where(p => p.GroupID == 7 && p.InterfixID == n.Id && p.ImageType == 1).ToList(),

                            BandSawImage=(from b in IContract.Entities where b.GroupID == 7 && b.InterfixID == n.Id && b.ImageType == 1 select b.ImagePath+b.FileName).ToList(),
                            //SubscribeImage = IContract.Entities.Where(p => p.GroupID == 7 && p.InterfixID == n.Id && p.ImageType == 2).ToList(),
                            SubscribeImage = (from s in IContract.Entities where s.GroupID == 7 && s.InterfixID == n.Id && s.ImageType == 2 select s.ImagePath + s.FileName).ToList(),
                            //DownPaymentImage = IContract.Entities.Where(p => p.GroupID == 7 && p.InterfixID == n.Id && p.ImageType == 3).ToList(),
                            DownPaymentImage = (from d in IContract.Entities where d.GroupID == 7 && d.InterfixID == n.Id && d.ImageType == 3 select d.ImagePath + d.FileName).ToList()

                        };

            string[] state = entity.State.Split(',');
            query = query.Where(p => state.Contains(p.State.ToString()));
            if (!String.IsNullOrEmpty(entity.Search))
            {
                query = query.Where(p => p.DecorationCompanyName.IndexOf(entity.Search) != -1 || p.IntermediaryName.IndexOf(entity.Search) != -1 || p.UserName.IndexOf(entity.Search) != -1 || p.CustomerName.IndexOf(entity.Search) != -1 || p.CustomerPhone.IndexOf(entity.Search) != -1 || p.UserPhone.IndexOf(entity.Search) != -1 || p.Id.ToString() == entity.Search);
            }

            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.SubscribeTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.pageIndex - 1) * entity.pageSize).Take(entity.pageSize)
                : null;

            var result = new AjaxResult("成功", AjaxResultType.Success, (total > 0 ? query.ToList() : new List<DecorationRunningListModel>()));
            return Token(result, "");
        }

        [Description("API-装修报备审批列表")]
        public IHttpActionResult ttGetDecorationFilingList()
        {
            Model.DbModels.Organization.Staff staff = SContract.GetByKey(BaseWebApiExt.GetStaffIDByToken());
            var query = from n in DRContract.Entities
                        join u1 in SContract.Entities on n.OriginStaffID equals u1.Id into eu1
                        from eu1d in eu1.DefaultIfEmpty()
                        join u2 in SContract.Entities on n.SellStaffID equals u2.Id into eu2
                        from eu2d in eu2.DefaultIfEmpty()
                        join s in DRSContract.Entities on n.State equals s.Id into s2
                        from s2d in s2.DefaultIfEmpty()
                        where n.State == 1 && n.AgentID == staff.AgentID
                        select new DecorationRunningListModel
                        {
                            BandSawTime = n.BandSawTime,
                            DecorationCompanyID = n.DecorationCompanyID,
                            DecorationCompanyName = n.DecorationCompanyName == null ? "" : n.DecorationCompanyName,
                            CompleteTime = n.CompleteTime,
                            CustomerID = n.CustomerID,
                            CustomerName = n.CustomerName == null ? "" : n.CustomerName,
                            CustomerPhone = n.CustomerPhone == null ? "" : n.CustomerPhone,
                            DownPaymentTime = n.DownPaymentTime,
                            FilingTime = n.FilingTime,
                            Id = n.Id,
                            IntermediaryID = n.IntermediaryID,
                            IntermediaryName = n.IntermediaryName == null ? "" : n.IntermediaryName,
                            OriginStaffID = n.OriginStaffID,
                            OriginStaffName = eu1d.Name == null ? "" : eu1d.Name,
                            Remark = n.State == 3 ? n.FilingAuditingRemark : n.Remark,
                            SellStaffID = n.SellStaffID,
                            SellStaffName = eu2d.Name == null ? "" : eu2d.Name,
                            State = n.State,
                            StateName = s2d.Name == null ? "" : s2d.Name,
                            SubscribeTime = n.SubscribeTime,
                            TotalPrice = n.TotalPrice,
                            UserID = n.UserID,
                            UserName = n.UserName == null ? "" : n.UserName,
                            UserPhone = n.UserPhone == null ? "" : n.UserPhone,
                            Area = n.Area,
                            CustomerAddress = n.CustomerAddress == null ? "" : n.CustomerAddress
                        };
            var result = new AjaxResult("成功", AjaxResultType.Success, query.ToList());
            return Token(result, "");

        }
        //State :    1 报备待审 2 报备通过 3 报备驳回 4 已带看 5 已交订金 6 已付首款 7 已备案 8 已完成
        //state:   //1 报备待审 2 报备通过 3 报备驳回 4 已到店 5 已交定金 6 已付首款 7 验收  8 退单 
        //ReturnState : 退货状态 默认-0，退单待审核-1，其他-其他
        [Description("API-更新流程状态")]
        public IHttpActionResult ttUpdateRunningState([FromBody]AuditingStateParamsModel entity)
        {
            if (entity == null)
            {
                var result = new AjaxResult("审核失败", AjaxResultType.Error);
                return Token(result, "");
            }

            var query = DRContract.GetByKey(entity.Id);

            if (query == null)
            {
                var result = new AjaxResult("审核失败", AjaxResultType.Error);
                return Token(result, "");
            }

            try
            {
                //获取StaffID
                int staffid = BaseWebApiExt.GetStaffIDByToken();

                int count = 0;//更新结果

                if (query.ReturnState.Equals(1))//没退房
                {
                    int newState = query.State;

                    switch (query.State)
                    {
                        case 1://报备待审
                            if (entity.AuditingType.Equals(1))//同意
                            {
                                newState = 2;
                            }
                            else//不同意
                            {
                                newState = 3;
                            }
                            count = DRContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { State = newState, FilingAuditingStaffID = staffid, FilingAuditingRemark = entity.Remark, FilingAuditingTime = DateTime.Now });
                            break;
                        case 2://报备通过
                            newState = 4;
                            count = DRContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { State = newState, BandSawStaffID = staffid, BandSawTime = DateTime.Now });
                            break;
                        case 3://报备驳回
                            break;
                        case 4://到店量尺
                            newState = 5;
                            count = DRContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { State = newState, SubscribeStaffID = staffid, SubscribeTime = DateTime.Now });
                            break;
                        case 5://已交定金
                            newState = 6;
                            count = DRContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { State = newState, DownPaymentStaffID = staffid, DownPaymentMoney = entity.Money, DownPaymentTime = DateTime.Now });
                            break;
                        case 6://已付首款
                            newState = 7;//验收完成
                            count = DRContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { State = newState, CompleteStaffID = staffid, CompleteTime = DateTime.Now });
                            break;
                        case 7://验收完成                        
                            break;
                        default:
                            break;
                    }
                }
                else//退房审核
                {
                    int newState2 = query.ReturnState;

                    switch (query.ReturnState)
                    {
                        case 0:
                            newState2 = 1;
                            count = DRContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { ReturnState = newState2, ReturnAuditingStaffID = staffid, ReturnAuditingTime = DateTime.Now });
                            break;
                        case 1:
                            if (entity.AuditingType.Equals(1))//同意
                            {
                                newState2 = 2;
                            }
                            else//不同意
                            {
                                newState2 = 0;
                            }
                            count = DRContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { ReturnState = newState2, ReturnAuditingStaffID = staffid, ReturnAuditingRemark = entity.Remark, ReturnAuditingTime = DateTime.Now });
                            break;
                        case 3:
                            break;
                        default:
                            break;
                    }
                }

                if (count > 0)
                {
                    var result = new AjaxResult("审核成功", AjaxResultType.Success);
                    return Token(result, "");
                }
                else
                {
                    var result = new AjaxResult("审核失败", AjaxResultType.Error);
                    return Token(result, "");
                }
            }
            catch (Exception ex)
            {
                var result = new AjaxResult("审核异常", AjaxResultType.Error);
                return Token(result, "");
            }

        }

    }
}